package com.gitee.flyzing.jxt;

import java.io.*;
import java.util.*;

import com.gitee.flyzing.jxt.component.JXTSheet;
import com.gitee.flyzing.jxt.test.Product;
import com.google.gson.Gson;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * java excel模板导出
 * @author yaoguangyao
 * @Date 2021年6月29日
 */
public class JXTemplate {
	private XSSFWorkbook workbook;
	private List<JXTSheet> jxtSheets = new ArrayList<>();

	/**
	 * @param tfile
	 */
	public JXTemplate(String tfile) {
		try {
			InputStream in = this.getClass().getResourceAsStream(tfile);
			this.workbook = new XSSFWorkbook(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void clear() {
		this.jxtSheets.clear();
	}

	/**
	 * 解析sheet
	 * @throws IOException
	 */
	public void parseSheet(int sheetIndex, Map datas) {
		XSSFSheet sheet = this.workbook.getSheetAt(sheetIndex);
		String sheetName = this.workbook.getSheetName(sheetIndex);
		JXTSheet jxtSheet = JXTSheet.createJXTSheet(sheet,sheetName, datas);
		jxtSheets.add(jxtSheet);

		Gson gson = new Gson();
		System.out.println(gson.toJson(jxtSheet));
	}


	/**
	 * 导出到输出流
	 * @param out
	 * @throws IOException
	 */
	public void export(OutputStream out) throws IOException {
		if (jxtSheets.size() > 0) {
			XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
			for (int i = 0; i < jxtSheets.size(); i++) {
				JXTSheet jxtSheet = jxtSheets.get(i);
				jxtSheet.createXSSFSheet(xssfWorkbook, i);
			}

			try {
				xssfWorkbook.write(out);
			} finally {
				out.flush();
				out.close();
			}
		}
	}

//	public static void main(String[] args) {
//		List products = new ArrayList();
//		Product product = new Product();
//		product.setProductNo("p001");
//		product.setProductName("花生");
//		product.setProductNum(100);
//		products.add(product);
//
//		product = new Product();
//		product.setProductNo("p002");
//		product.setProductName("可乐");
//		product.setProductNum(50);
//		products.add(product);
//
//		product = new Product();
//		product.setProductNo("p003");
//		product.setProductName("薯片");
//		product.setProductNum(10);
//		products.add(product);
//
//		Map datas = new HashMap();
//		datas.put("productList", products);
//
//		JXTemplate jxTemplate = new JXTemplate("/jxt/test1.xlsx");
//		try {
//			FileOutputStream fos = new FileOutputStream("out.xlsx");
//			jxTemplate.parseSheet(0, datas);
//			jxTemplate.parseSheet(1, datas);
//			jxTemplate.export(fos);
//			fos.flush();
//			fos.close();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}

}
